<template>
  <basic-container>
    <div style="width:100%;min-height: 50px;padding-left:5px;display: inline-block;margin-bottom: 20px">
      <el-container>
        <el-container>
          <el-container>
            <el-main style="background: #fff!important">
              <div style="background:#fff;height: 50px;line-height: 50px;padding-left:5px ">
                产线名称：<avue-input v-model="realityLineName" style="width:180px;margin-right: 5px" placeholder="请输入产线名称" ></avue-input>
                <el-button type="primary" @click="saveRealityLine">保存</el-button>
              </div>
            </el-main>
          </el-container>
        </el-container>
      </el-container>
    </div>
    <template>
      <div class="form-designer"  v-loading="saveLoading">
        <el-container style="border: #e0e0e0 solid 1px;border-top:none">
          <el-aside width="240px">
            <el-header style="height:40px;text-align: center;line-height: 40px;width:240px;position: absolute;background: #fff">工序</el-header>
            <div style="height:800px;margin-top:45px">
                <el-button v-for="process in pfocProcessList" @click="addProcessNode(process.processName,process.id)" style="margin: 5px 5px;width:90%" >{{process.processName}}</el-button>
            </div>
          </el-aside>
          <el-main class="demo" style="border-left: 1px solid #e0e0e0;">
            <avue-flow :height="800"
                       width="100%"
                       style="min-height: 800px;"
                       ref="flow"
                       :option="option"
                       v-model="flowForm">
              <template #header="{node}" >
                {{(node || {}).name}}
                <i class="el-icon-delete"  style="float: right;line-height: 30px;margin-right: 2px" @click="deleteNode(node.id)"></i>
              </template>
              <template slot-scope="{node}">
                <el-collapse :ref="node.id+`Ref`"  @change="collapseChange(node.id)" :style="{width:'100%',zIndex:zIndexStyle}"  @mouseover.native="handleMouseEnter(node.id)"  @mouseout.native="handleMouseLeave(node.id)">
                  <el-collapse-item title="工序属性" name="1">
                    <el-descriptions  class="margin-top"  title="" :column="1" size="small" border >
                        <el-descriptions-item label="工段">
                          <!--<avue-select v-model="form[node.id+`_workshopSection`]" filterable clearable  dialogWidth="100%"   placeholder="请选择工段"  :props="{label: 'label',value: 'value'}"  :dic="workshopSectionList" ></avue-select>-->
                          <el-select v-model="form[node.id+`_workshopSection`]"  :ref="node.id+`workshopSectionRef`" placeholder="请选择工段"  :popper-append-to-body="false" filterable clearable  dialogWidth="100%"  >
                            <el-option
                              v-for="item in workshopSectionList"
                              @mouseover.native="handleMouseEnter(node.id)"  @mouseout.native="handleMouseLeave(node.id)"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                            </el-option>
                          </el-select>
                        </el-descriptions-item>
                        <el-descriptions-item label="设备">
                          <deviceSelect   :ref="node.id+`_devicePage`"
                                          v-model="form[node.id+`_device`]"
                                          attributeName="设备"
                                          attributeField="device"
                                          :deviceClass="form[node.id+`_deviceClass`]"
                                          :nodeId = "node.id"
                                          :seleteOptions="deviceList"
                                          :defaultVal ="form[node.id+`_device`]"
                                          @handleMouseEnter="handleMouseEnter(node.id)"  @handleMouseLeave="handleMouseLeave(node.id)"
                                          @handleSelectData = "handleSelectData"/>
                          <div element-loading-text="拼命加载中"  element-loading-spinner="el-icon-loading" v-loading="deviceList.length==0"></div>
                        </el-descriptions-item>

                        <el-descriptions-item label="工具">
                          <deviceSelect   :ref="node.id+`_toolPage`"
                                          v-model="form[node.id+`_tool`]"
                                          attributeName="工具"
                                          attributeField="tool"
                                          :deviceClass="form[node.id+`_deviceClass`]"
                                          :nodeId = "node.id"
                                          :seleteOptions="toolList"
                                          :defaultVal ="form[node.id+`_tool`]"
                                          @handleMouseEnter="handleMouseEnter(node.id)"  @handleMouseLeave="handleMouseLeave(node.id)"
                                          @handleSelectData = "handleSelectData"/>
                          <div element-loading-text="拼命加载中"  element-loading-spinner="el-icon-loading" v-loading="toolList.length==0"></div>
                        </el-descriptions-item>

                        <el-descriptions-item label="夹具">
                          <deviceSelect   :ref="node.id+`_clampPage`"
                                          v-model="form[node.id+`_clamp`]"
                                          attributeName="夹具"
                                          attributeField="clamp"
                                          :deviceClass="form[node.id+`_deviceClass`]"
                                          :nodeId = "node.id"
                                          :seleteOptions="clampList"
                                          @handleMouseEnter="handleMouseEnter(node.id)"  @handleMouseLeave="handleMouseLeave(node.id)"
                                          :defaultVal ="form[node.id+`_clamp`]"
                                          @handleSelectData = "handleSelectData"/>
                          <div element-loading-text="拼命加载中"  element-loading-spinner="el-icon-loading" v-loading="clampList.length==0"></div>
                        </el-descriptions-item>
                        <el-descriptions-item label="设备分类">
                           <!--<avue-select   v-model="form[node.id+`_deviceClass`]" filterable clearable   dialogWidth="100%"  multiple placeholder="请选择设备分类"  :props="{label: 'label',value: 'value'}"  :dic="deviceClassList" @change="deviceClassChange(node.id)"></avue-select>-->
                          <el-select v-model="form[node.id+`_deviceClass`]"  :ref="node.id+`deviceClassRef`" placeholder="请选择设备分类"  :popper-append-to-body="false" filterable clearable  dialogWidth="100%"  multiple @change="deviceClassChange(node.id)">
                            <el-option
                              v-for="item in deviceClassList"
                              @mouseover.native="handleMouseEnter(node.id)"  @mouseout.native="handleMouseLeave(node.id)"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                            </el-option>
                          </el-select>
                        </el-descriptions-item>
                    </el-descriptions>
                  </el-collapse-item>
                </el-collapse>
              </template>
            </avue-flow>

          </el-main>
        </el-container>
      </div>
    </template>
  </basic-container>
</template>

<script>
    import {getPfocProcessList } from '@/api/pfoc/pfocprocess'
    import { getObj} from '@/api/pfoc/factorysettings' //获取当前工厂信息
    import { getDevice,getDeviceClassList} from '@/api/hengdong/pfocinterface'//获取设备相关
    import { saveLine } from '@/api/pfoc/realityproductlinemain' //产线相关
    /**引入设备下拉框*/
    import deviceSelect from '@/views/pfoc/realityproductline/custom-select'

    export default {
        name: "add-line",
        components: {
            //设备下拉框
            deviceSelect,
        },
        props:{
            workshopSectionList:{//工段集合
                type:Array
            },
        },
        data() {
            return {
                count: 0,
                flowForm:'',
                nodeCount:0,//节点下标
                form: [],//提交时数据集合
                pfocProcessList:[],//工序集合
                option: {
                    name: null,
                    nodeList: [],//工序节点集合
                    lineList: [],//工序各节点指向顺序集合
                },
                realityLineName:null,//产线名称
                deviceList:[],//设备集合
                clampList:[],//夹具集合
                toolList:[],//工具集合
                deviceClassList:[],//设备分类集合
                organizationId:null,//组织ID
                organizationName:null,//组织名称
                saveLoading:false,//保存时遮罩开关
                zIndexStyle:"",
            };
        },
        created() {
            //获取当前工厂信息
            this.getFactoryInfo();
            //获取设备分类数据
            this.getDeviceClassListData();
        },
        computed: {
            nodeList () {
                return this.option.nodeList
            }

        },
        mounted() {
            this.nodeCount = this.option.nodeList.length;//初始化节点下标
            //获取工序
            this.getPfocProcessListData();

        },
        methods: {
            /**获取工序*/
            getPfocProcessListData(){
                getPfocProcessList().then(response => {
                    this.pfocProcessList=response.data.data;
                })
            },
            /**获取工厂信息*/
            getFactoryInfo() {
                const factoryId=1;
                getObj(factoryId).then(response => {
                    this.organizationId = response.data.data.menuId;//组织ID
                    this.organizationName = response.data.data.organizationName;//组织名称
                    //获取工厂设备集合
                    this.getFactoryDeviceList();
                })
            },
            /**获取工厂设备集合*/
            getFactoryDeviceList(){
                var obj={
                    position:this.organizationName,//设置组织查询条件
                }
                getDevice(obj).then(response => {
                    this.deviceList = response.data.data;//设备集合
                    for(var i =0; i<this.deviceList.length;i++){
                        if(this.deviceList[i].deviceClass==20){//组织下工具夹具筛选
                            this.clampList.push(this.deviceList[i]);//夹具集合
                            this.toolList.push(this.deviceList[i]);//工具集合
                        }
                    }
                    //重置自定义下拉框选项
                    for (var i = 0; i < this.option.nodeList.length; i++) {
                        var nodeId = this.option.nodeList[i].id;
                        var obj = new Object();//创建对象
                        //循环工序属性取出每个工序的个属性数据加入到对象
                        let refDevice = nodeId + "_devicePage";//获取到当前的ref
                        this.$nextTick(() => {
                            this.$refs[refDevice].deviceSelectInit();
                        })
                        let refTool = nodeId + "_toolPage";//获取到当前的ref
                        this.$nextTick(() => {
                            this.$refs[refTool].deviceSelectInit();
                        })
                        let refClamp = nodeId + "_clampPage";//获取到当前的ref
                        this.$nextTick(() => {
                            this.$refs[refClamp].deviceSelectInit();
                        })
                    }
                })
            },
            /**获取设备分类数据*/
            getDeviceClassListData(){
                getDeviceClassList().then(response => {
                    this.deviceClassList=response.data.data;
                })
            },

            /**添加工序*/
            addProcessNode(name,id,workshopSection){//工序名称，工序ID
                this.$set(this.form, "node"+this.nodeCount + "_processName", name);//注册动态节点-当前工序名称
                this.$set(this.form, "node"+this.nodeCount + "_processId", id);//注册动态节点-当前工序ID
                this.$set(this.form, "node"+this.nodeCount + "_deviceClass", null);//注册动态节点-当前工序设备分类
                this.$set(this.form, "node"+this.nodeCount + "_device", null);//注册动态节点-当前工序设备
                this.$set(this.form, "node"+this.nodeCount + "_tool", null);//注册动态节点-当前工序工具
                this.$set(this.form, "node"+this.nodeCount + "_clamp", null);//注册动态节点-当前工序夹具
                this.$set(this.form, "node"+this.nodeCount + "_deviceName",null);//注册动态节点-设备名称
                this.$set(this.form, "node"+this.nodeCount + "_toolName",null);//注册动态节点-工具名称
                this.$set(this.form, "node"+this.nodeCount + "_clampName",null);//注册动态节点-夹具名称
                this.$set(this.form, "node"+this.nodeCount + "_workshopSection",null);//注册动态节点-工段

                this.$refs.flow.addNode(name,id,this.nodeCount);//添加节点
                this.nodeCount=this.nodeCount+1;//更新节点下标
                // console.log(this.form)
                // console.log(this.option.nodeList)
            },
            /**删除工序*/
            deleteNode(id){
                var t = this;
                this.$confirm("确定要删除节点" + id + "?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    closeOnClickModal: !1
                }).then((function() {
                    t.$refs.flow.deleteNode(id);
                    t.option.nodeList = t.option.nodeList;
                    t.$delete(t.form, id + "_processName");//删除动态节点-当前工序名称
                    t.$delete(t.form, id + "_processId");//删除动态节点-当前工序ID
                    t.$delete(t.form, id + "_deviceClass");//删除动态节点-动态变量-设备类型
                    t.$delete(t.form, id + "_device");//删除动态节点-动态变量-设备
                    t.$delete(t.form, id + "_tool");//删除动态节点-动态变量-工具
                    t.$delete(t.form, id + "_clamp");//删除动态节点-动态变量-夹具
                    t.$delete(t.form, id + "_deviceName");//删除动态节点-设备名称
                    t.$delete(t.form, id + "_toolName");//删除动态节点-工具名称
                    t.$delete(t.form, id + "_clampName");//删除动态节点-夹具名称
                    t.$delete(t.form, id + "_workshopSection");//删除动态节点-工段
                    console.log(t.form)
                })).catch((function() {}))
            },
            /**保存产线*/
            saveRealityLine(){

                if(this.validatenull(this.realityLineName)){
                    this.$message.warning("产线名称不能为空。")
                    return;
                }
                if(this.validatenull(this.option.nodeList)){
                    this.$message.warning("请选择工序创建产线。")
                    return;
                }
                //组装需要提交的数据-实际产线主表数据组装
                var params = {};//主表参数集合
                params.realityLineName = this.realityLineName;//产线名称
                params.processNodes = JSON.stringify(this.option.nodeList);//工序节点集合（其中mark字段为工序ID）
                params.processNodeLine = JSON.stringify(this.option.lineList);//工序各节点指向顺序集合

                //组装需要提交的数据-实际产线子表数据组装
                var objArr = [];
                var messageArr=[];
                //循环工序节点集合
                for(var i=0;i<this.option.nodeList.length;i++){
                    var message = new Object();//未选择数据时错误消息对象
                    var error =[];//未选择数据时错误消息集合
                    var obj = new Object();//创建对象

                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_workshopSection'])) {
                        obj['workshopSection'] = this.form[this.option.nodeList[i].id + '_workshopSection'];
                    }else{
                        obj['workshopSection'] = null;
                        error.push("工段");
                    }

                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_device'])) {
                        obj['device'] = this.form[this.option.nodeList[i].id + '_device'].toString();
                    }else{
                        obj['device'] = null;
                    }
                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_tool'])) {
                        obj['tool'] = this.form[this.option.nodeList[i].id + '_tool'].toString();
                    }else{
                        obj['tool'] = null;
                    }
                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_clamp'])) {
                        obj['clamp'] = this.form[this.option.nodeList[i].id + '_clamp'].toString();
                    }else{
                        obj['clamp'] = null;
                    }
                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_deviceName'])){
                        obj["deviceNames"] = this.form[this.option.nodeList[i].id + '_deviceName'];
                    }else{
                        obj["deviceNames"] = null;
                    }
                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_toolName'])){
                        obj["toolNames"] = this.form[this.option.nodeList[i].id + '_toolName'];
                    }else{
                        obj["toolNames"] = null;
                    }
                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_clampName'])){
                        obj["clampNames"] = this.form[this.option.nodeList[i].id + '_clampName'];
                    }else{
                        obj["clampNames"] = null;
                    }

                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_deviceClass'])) {//设备分类
                        obj['deviceClass'] = this.form[this.option.nodeList[i].id + '_deviceClass'].toString();
                    }else{
                        obj['deviceClass'] = null;
                    }
                    if(error.length>0){
                        message["工序"] = this.option.nodeList[i].name;
                        message["属性"] = error;
                        messageArr.push(message);
                    }
                    obj['processId'] = this.option.nodeList[i].mark;//取出工序ID加入对象
                    obj['processName'] = this.option.nodeList[i].name;//取出工序名称加入对象
                    obj['nodeId'] = this.option.nodeList[i].id;
                    obj['organizationName'] = this.organizationName;//组织名称
                    obj['organizationId'] = this.organizationId;//组织ID
                    //最后加入提交数据数组
                    objArr.push(obj)
                }
                //漏填提醒
                if(!this.validatenull(messageArr)){
                    this.$message.warning(JSON.stringify(messageArr)+"——等数据未选择。")
                    return;
                }

                var data={
                    realityProductLineMain:params,
                    realityProductLineDetailsList:objArr,
                }
                this.saveLoading=true;
                //提交
                saveLine(data).then(response => {
                    if(response.data.data=="1") {
                        this.$message.warning(
                            {
                                message: "新增产线失败，产线：【"+this.realityLineName+"】已存在，已勿重复添加。",
                                duration: 5000 // 设置时长为5秒
                            });
                        this.saveLoading = false;
                    }else{
                        this.$message.success("产线添加成功。")
                        this.saveLoading = false;
                        this.$emit('closeAdd');//关闭新增页面
                    }
                }).catch(() => {
                    this.saveLoading = false;
                });
            },

            //下拉框选择后返回数据
            handleSelectData(obj){
                this.form[obj.nodeId+"_"+obj.attributeField] = obj.deviceSn;
                this.$set(this.form,obj.nodeId+"_"+obj.attributeField + "Name", obj.deviceName);//注册动态节点-设备名称
            },
            //设备分类选择
            deviceClassChange(nodeId){
                 this.$set(this.form, nodeId+ "_device", null);//注册动态节点-设备
                 this.$set(this.form, nodeId+ "_deviceName", null);//注册动态节点-设备名称
                 let refDevice = nodeId + "_devicePage";//获取到当前的ref
                  this.$nextTick(() => {
                    this.$refs[refDevice].deviceSelectInit();
                })
            },
            //鼠标移到置顶
            handleMouseEnter(nodeId) {
                //属性鼠标移到展开
                // this.$set(this.showActive, nodeId, ['1']);
                let ref = nodeId+"Ref";//获取到当前的ref
                this.$refs[ref].$parent.$refs.node.style.zIndex="999999";
                this.zIndexStyle="1";

            },
            //鼠标移开取消置顶
            handleMouseLeave(nodeId) {
                //属性鼠标移开关闭
                // this.$set(this.showActive, nodeId, []);
                let ref = nodeId+"Ref";//获取到当前的ref
                this.$refs[ref].$parent.$refs.node.style.zIndex="2";
                this.zIndexStyle="";

            },
            //伸缩面板切换
            collapseChange(nodeId){
                let refDevice = nodeId + "_devicePage";//获取到当前的ref
                let refTool = nodeId + "_toolPage";//获取到当前的ref
                let refClamp = nodeId + "_clampPage";//获取到当前的ref
                let workshopSectionRef = nodeId+"workshopSectionRef";
                let deviceClassRef = nodeId+"deviceClassRef";
                this.$nextTick(() => {
                    this.$refs[refDevice].removeBlur(nodeId);
                    this.$refs[refTool].removeBlur(nodeId);
                    this.$refs[refClamp].removeBlur(nodeId);
                });
                this.$refs[workshopSectionRef].blur();
                this.$refs[deviceClassRef].blur();
            }
        }
    };
</script>

<style scoped>
  /deep/.avue-flow__node{
    height: auto!important;
  }
  /deep/ .avue-flow__node-header {
    line-height: 30px;
  }
  /deep/.el-descriptions__title {
    font-size: 14px;
    font-weight: 400;
    margin-top: 5px;
  }


  /*以下样式是打印的时候avue表格错乱修正方式（主要是序号列和操作列固定影响的）*/
  /deep/.el-table__fixed{
    display: none!important;
  }
  /deep/.el-table__fixed-right{
    display: none!important;
  }
  /deep/.el-table__cell.is-hidden>*{visibility:visible !important;}

  /deep/ .avue-grid{
    display: none!important;
  }
  /deep/.el-main{
    background:#fff !important;
  }
  /deep/.el-card__body{
    padding: 0px!important;
  }
  /*去掉滚动条样式*/
  .demo::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
  .demo {
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
